package main

import (
	"flag"
	"fmt"
	"go-chi-restful-api/dao"
	"go-chi-restful-api/settings"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func main() {
	// 日志设置，加载配置，数据库启动，注册路由，启动监听服务
	// 配置文件路径解析
	var confFile string
	flag.StringVar(&confFile, "conf", "./conf/config.yaml", "配置文件路径")
	flag.Parse()

	if err := settings.Init(); err != nil {
		fmt.Printf("load config failed, err: %s \n", err)
		return
	}

	if err := dao.InitMySQL(settings.Conf.MySQLConfig); err != nil {
		fmt.Printf("init mysql failed, err: %s \n", err)
		return
	}

	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)

	r.Group(func(r chi.Router) {
		r.Get("/", HelloWorld)
		r.Get("/{columnID}", GetColumn)                        // 专栏详情页
		r.Get("/{columnID}/directory", GetColumnDirectory)     // 专栏目录
		r.Get("/{columnID}/{chapterID}", GetColumnChapterText) // 章节内容
	})

	// 启动服务器
	http.ListenAndServe(fmt.Sprintf(":%d", settings.Conf.Port), r)
}

func HelloWorld(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func GetColumn(w http.ResponseWriter, r *http.Request) {
	id := chi.URLParam(r, "columnID")

	column, err := dao.GetColumnByID(id)
	if err != nil {
		panic(fmt.Errorf("dao.GetColumnByID(id) failed, err:%s", err))
	}

	fmt.Fprintf(w, "专栏名：%s\n 在看人数：%d\n 内容详情：%s\n",
		column.ColumnName, column.ColumnReaderNums, column.ColumnDetail)

}

func GetColumnDirectory(w http.ResponseWriter, r *http.Request) {
	id := chi.URLParam(r, "columnID")

	chapters, err := dao.GetColumnDirectoryByID(id)

	if err != nil {
		panic(fmt.Errorf("dao.GetColumnDirectoryByID(id) failed, err:%s", err))
	}

	for _, chapter := range chapters {
		fmt.Fprintf(w, "章节标题：%s\n", chapter.ChapterTitle)
	}
}

func GetColumnChapterText(w http.ResponseWriter, r *http.Request) {
	columnID := chi.URLParam(r, "columnID")
	chapterID := chi.URLParam(r, "chapterID")

	chapter, err := dao.GetColumnChapterTextByID(chapterID, columnID)
	if err != nil {
		panic(fmt.Errorf("dao.GetColumnChapterTextByID(id) failed, err:%s", err))
	}

	fmt.Fprintf(w, "章节标题：%s\n 章节内容：%s", chapter.ChapterTitle, chapter.ChapterContent)
}
